package com.example.weather.api;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.weather.R;
import com.example.weather.api.bean.Air;
import com.example.weather.api.bean.NowWeather;
import com.example.weather.api.dto.AirDTO;
import com.example.weather.api.dto.LocationDTO;
import com.example.weather.api.dto.NowDTO;
import com.example.weather.utils.HttpUtil;
import com.example.weather.utils.HttpsUtil;
import com.example.weather.utils.IconUtils;
import com.google.gson.Gson;
import com.squareup.moshi.Moshi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 天气API来自和风天气：https://www.qweather.com
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    // 使用Web API的key进行模拟测试，在Connection中增加user-agent设置
    public static final String APP_KEY = "80f794cc920c497fb675c679d35b307b";
    public static final String CITY_URL = "https://geoapi.qweather.com/v2/city/lookup?key=80f794cc920c497fb675c679d35b307b&";
    public static final String NOW_URL = "https://devapi.qweather.com/v7/weather/now?key=80f794cc920c497fb675c679d35b307b&";
    public static final String AIR_URL = "https://devapi.qweather.com/v7/air/now?key=80f794cc920c497fb675c679d35b307b&";

    private static final int TYPE_CITY = 1;
    private static final int TYPE_NOW = 2;
    private static final int TYPE_AIR = 3;

    private TextView tvCity;
    private ImageView ivIcon;
    private TextView tvWeather;
    private TextView tvTemp;
    private TextView tvWind;
    private TextView tvPm;
    private RelativeLayout mainLayout;

    private SparseArray<String> cities;
    private String currentCity;
    private Map<String, String> imageUrls;
    private String currentImageUrl;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TYPE_CITY:
                    String currentCityId = parseLocation((String) msg.obj);
                    if (currentCityId != null) {
                        getJson(TYPE_NOW, NOW_URL + "location=" + currentCityId);
                        getJson(TYPE_AIR, AIR_URL + "location=" + currentCityId);
                    }
                    break;
                case TYPE_NOW:
                    NowWeather now = parseNowByGson((String) msg.obj);
                    if (now != null) {
                        // 1. 设置天气的icon
                        String condCode = now.getIcon();
                        int hour = 0;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            // minSdkVersion >= 26
                            LocalTime nowTime = LocalTime.now();
                            hour = nowTime.getHour();
                        } else {
                            // 传统做法
                            Calendar today = Calendar.getInstance();
                            hour = today.get(Calendar.HOUR_OF_DAY);
                        }
                        if (hour > 6 && hour < 18) {
                            ivIcon.setImageResource(IconUtils.getDayIconDark(condCode));
                        } else {
                            ivIcon.setImageResource(IconUtils.getNightIconDark(condCode));
                        }
                        tvCity.setText(currentCity);
                        tvWeather.setText(now.getText());
                        tvTemp.setText(now.getTemp() + "℃");
                        tvWind.setText(now.getWindDir() + now.getWindScale() + "级");
                        currentImageUrl = imageUrls.get(now.getText());
                    }
                    currentImageUrl = currentImageUrl != null ? currentImageUrl : imageUrls.get("默认");
                    loadBackground(currentImageUrl);
                    break;
                case TYPE_AIR:
                    Air air = parseAirByFastjson((String) msg.obj);
                    if (air != null) {
                        tvPm.setText("空气" + air.getCategory());
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
    }

    private void initView() {
        mainLayout = findViewById(R.id.main_layout);
        tvCity = findViewById(R.id.tv_city);
        ivIcon = findViewById(R.id.iv_icon);
        tvWeather = findViewById(R.id.tv_weather);
        tvTemp = findViewById(R.id.tv_temp);
        tvWind = findViewById(R.id.tv_wind);
        tvPm = findViewById(R.id.tv_pm);

        findViewById(R.id.btn_nj).setOnClickListener(this);
        findViewById(R.id.btn_bj).setOnClickListener(this);
        findViewById(R.id.btn_sh).setOnClickListener(this);
        findViewById(R.id.btn_gz).setOnClickListener(this);
    }

    private void initData() {
        // 初始化城市名称与按钮的对应关系列表
        cities = new SparseArray<>();
        cities.put(R.id.btn_nj, "南京");
        cities.put(R.id.btn_bj, "北京");
        cities.put(R.id.btn_sh, "上海");
        cities.put(R.id.btn_gz, "广州");
        currentCity = cities.get(R.id.btn_nj);

        // 初始化天气与背景图URL的对应关系
        imageUrls = new HashMap<>();
        imageUrls.put("多云", "https://b.zol-img.com.cn/sjbizhi/images/10/320x510/1574629460487.jpg");
        imageUrls.put("晴", "https://sjbz-fd.zol-img.com.cn/t_s320x510c5/g5/M00/0F/09/ChMkJlfJQWSIIEmVAAQzGYKI3fwAAU7cwLGCn8ABDMx195.jpg");
        imageUrls.put("雨", "https://b.zol-img.com.cn/sjbizhi/images/10/320x510/157367915321.jpg");
        imageUrls.put("阴", "https://sjbz-fd.zol-img.com.cn/t_s320x510c5/g6/M00/04/08/ChMkKV8iKQSIQf3QABP2dG0tSfEAAASAAFHVTwAE_aM847.jpg");
        imageUrls.put("默认", "https://sjbz-fd.zol-img.com.cn/t_s320x510c5/g5/M00/02/00/ChMkJl3xtFSIMSpNABawKeTgRp4AAvtLAEsyP8AFrBB136.jpg");

        // 根据城市名称获取网络请求的json字符串
        getJson(TYPE_CITY, CITY_URL + "location=" + currentCity);
    }

    @Override
    public void onClick(View view) {
        currentCity = cities.get(view.getId());
        getJson(TYPE_CITY, CITY_URL + "location=" + currentCity);
    }

    private void getJson(int type, String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 1. 获取连接
                    StringBuilder builder = new StringBuilder();
                    HttpURLConnection connection = HttpUtil.getConnection(url);
                    // 2. 读取json字符串
                    InputStream is = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                    reader.close();
                    is.close();
                    // 给Handler发送消息
                    Message msg = Message.obtain();
                    msg.what = type;
                    msg.obj = builder.toString();
                    MainActivity.this.handler.sendMessage(msg);

                    Log.d("MainActivity", builder.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getJsonByOkhttp(int type, String url) {
        // 1. 创建请求对象
        OkHttpClient client = new OkHttpClient();
        // 2. 构建请求数据
        Request request = new Request.Builder()
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
                        "AppleWebKit/537.36 (KHTML, like Gecko) " +
                        "Chrome/86.0.4240.111 " +
                        "Safari/537.36 Edg/86.0.622.51")
                .url(url).build();
        // 3. 发出请求
        client.newCall(request).enqueue(new Callback() {
            // 4. 处理请求响应的回调
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("MainActivity", "请求出错，" + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "网络请求出错" + e.toString(),
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                if (response.isSuccessful() && body != null) {
                    Message msg = Message.obtain();
                    msg.what = type;
                    msg.obj = body.string();
                    MainActivity.this.handler.sendMessage(msg);
                } else {
                    Log.i("MainActivity", "数据为null，" + response.message());
                }
            }
        });
    }
//        new Thread(() -> {
//            try (Response response = new OkHttpClient().newCall(request).execute()) {
//                ResponseBody body = response.body();
//                if (response.isSuccessful() && body != null) {
//                    Message msg = Message.obtain();
//                    msg.what = type;
//                    msg.obj = body.string();
//                    MainActivity.this.handler.sendMessage(msg);
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }).start();
//    }

    private String parseLocation(String json) {
        try {
            Moshi moshi = new Moshi.Builder().build();
            LocationDTO locationDTO = moshi.adapter(LocationDTO.class).fromJson(json);
            if (locationDTO != null && locationDTO.getCode().equals("200")) {
                return locationDTO.getLocation().get(0).getId();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private NowWeather parseNowByGson(String json) {
        NowDTO nowDTO = new Gson().fromJson(json, NowDTO.class);
        if (nowDTO != null && nowDTO.getCode().equals("200")) {
            return nowDTO.getNow();
        }
        return null;
    }

    private Air parseAirByFastjson(String json) {
        AirDTO airDTO = JSON.parseObject(json, AirDTO.class);
        if (airDTO != null && airDTO.getCode().equals("200")) {
            return airDTO.getNow();
        }
        return null;
    }

    private void loadBackground(String imageUrl) {
        Glide.with(MainActivity.this)
                .asBitmap()
                .load(imageUrl)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource,
                                                @Nullable Transition<? super Bitmap> transition) {
                        BitmapDrawable drawable = new BitmapDrawable(getResources(), resource);
                        mainLayout.setBackground(drawable);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                        mainLayout.setBackgroundResource(R.drawable.default_img);
                    }
                });
    }
}